package com.applet.applet_shangcheng.controller;

import com.alibaba.fastjson.JSONObject;
import com.applet.applet_shangcheng.dao.GoodsMapper;
import com.applet.applet_shangcheng.dao.UserMapper;
import com.applet.applet_shangcheng.entity.Goods;
import com.applet.applet_shangcheng.entity.Order;
import com.applet.applet_shangcheng.entity.User;
import com.applet.applet_shangcheng.service.OrderService;
import com.applet.applet_shangcheng.service.PayService;
import com.applet.applet_shangcheng.utlis.*;
import com.github.wxpay.sdk.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import static com.applet.applet_shangcheng.utlis.AppletUtil.getRandomStringByLength;

@RestController
@RequestMapping("/weixin/pay")
@Api(value="支付管理",tags={"支付管理"})
public class payController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PayService payService;


    //修改支付状态
    @ApiOperation(value="WX_根据回调地址修改支付状态//需要https")
    @RequestMapping("/notify")
    public void notifyWxPay(HttpServletRequest request) throws Exception {
        ServletInputStream is = request.getInputStream();
        //ByteOutputStream os = new ByteOutputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] arr = new byte[1024];
        int len;
        while ((len = is.read()) != -1) {
            os.write(arr, 0, len);
        }
        os.flush();
        os.close();
        is.close();
        String strXml = new String(String.valueOf(os));
        System.out.println(strXml);
        Map<String, String> map = WXPayUtil.xmlToMap(strXml);
        System.out.println(map);
    }

    //查询支付
    @ApiOperation(value="根据订单号查询支付状态")
    @RequestMapping("/select/native/{orderId}")
    public Result selectNative(@PathVariable("orderId") String order_id) {
        Map<String, String> map = payService.selectNative(order_id);
        String return_code = map.get("result_code");
        if (return_code.equals("FAIL")) {
            return new Result(false, StatusCode.ERROR, "查询支付失败", map);
        }
        return new Result(true, StatusCode.OK, "查询支付成功", map);
    }



    @RequestMapping("/create/native/{order_id}/{unit_price}")
    public Result createNative(@PathVariable("order_id") String order_id,
                               @PathVariable("unit_price")  String unit_price, HttpServletRequest request) throws Exception {
        //localhost:8899/weixin/pay/create/native?order_id=8888&unit_price=1
        //创建支付订单
        String spbill_create_ip = AppletUtil.getIpAddr(request);
        Map<String, Object> map = payService.createNative(order_id, unit_price, spbill_create_ip);
        String return_code = (String) map.get("return_code");
        if (return_code != null && return_code.equals("FAIL")) {
            return new Result(true, StatusCode.OK, "创建支付失败", map);
        }
        return new Result(true, StatusCode.OK, "创建支付成功", map);
    }
    //统一下单，接收openid
    @ApiOperation(value="创建订单order_id/订单号")
    @GetMapping("/wxjspay/{order_id}/{unit_price}")
    @ResponseBody
    public  Map<String, Object>  wxjspay(@PathVariable("order_id") String order_id,
                                         @PathVariable("unit_price")  String unit_price, HttpServletRequest request) throws Exception {
        String pay_url = WXConstVO.pay_url;
        //入参,将数据封装到map转xml
        Map<String,String>data= new HashMap<>();
        data.put("appid", WXConstVO.appId);// 小程序ID
        data.put("mch_id", WXConstVO.mch_id);// 商户号
        data.put("nonce_str", WXPayUtil.generateNonceStr());// 随机字符串
        data.put("body", "小程序支付");              //商品描述
        data.put("out_trade_no", order_id);         //商户订单号
        data.put("total_fee", unit_price);// 订单总金额，单位为分
        data.put("spbill_create_ip", AppletUtil.getIpAddr(request));//终端IP
        data.put("notify_url", "http://www.weixin.qq.com/wxpay/pay.php");// 回调地址
        data.put("trade_type", "JSAPI");//交易类型NATIVE,JSAPI
        //data.put("openid", WXConstVO.);//用户标识
        data.put("openid", "oKbmB4k_N4bdggUI_95A1uDZbPLg");//用户标识
        String signedXml = WXPayUtil.generateSignedXml(data,WXConstVO.key);//xml

        System.out.println(order_id+"+"+unit_price);
        //请求:httpclient
        HttpClient httpClient = new HttpClient(pay_url);
        httpClient.setXmlParam(signedXml);//请求参数
        httpClient.setHttps(true);        //请求方式
        httpClient.post();

        //响应结果xml转map
        String strXml = httpClient.getContent();
        Map<String, String> map = WXPayUtil.xmlToMap(strXml);
        System.out.println(map);
        String return_code = (String) map.get("return_code");//返回状态码
        String result_code = (String) map.get("result_code");//返回状态码
        //生成的随机字符串
        String nonce_str = getRandomStringByLength(32);
        Map<String, Object> response = new HashMap<String, Object>();//返回给小程序端需要的参数
        if (return_code .equals("SUCCESS")  && result_code.equals("SUCCESS")) {
            String prepay_id = (String) map.get("prepay_id");//返回的预付单信息
            response.put("nonceStr", nonce_str);
            response.put("resultCode", result_code);
            response.put("returnCode", return_code);
            response.put("package", "prepay_id=" + prepay_id);
            Long timeStamp = System.currentTimeMillis() / 1000;
            response.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误
            //拼接签名需要的参数
            String stringSignTemp = "appId=" +"wx24e555c077e702f3" + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
            //再次签名，这个签名用于小程序端调用wx.requesetPayment方法
            String paySign = PayUtil.sign(stringSignTemp,  "washimayun1302525820515014354439", "utf-8").toUpperCase();
            response.put("paySign", paySign);
        }

        response.put("appid", "wx24e555c077e702f3");
        return response;
    }

}
